import React, {Component} from 'react';
import {withRouter} from "react-router-dom";
import style from './ReleaseForum.module.less'
import  MdEditor  from 'md-editor-rt';
import 'md-editor-rt/lib/style.css';
import {Form, Input} from "antd";
import {createForumRequest, uploadForumRequest, uploadImgRequest} from "@requests/Forum";
import {toast} from "react-toastify";
let user = JSON.parse(sessionStorage.getItem("user"))
const formdata = new FormData()
class ReleaseForum extends Component {

    state={
        text:'',
        img:[],
        title:null,
        fourmId:null,
        FourmState:'idle'
    }
    setTitle = (event) => {
        this.setState({
            title:event.target.value
        })
    }
    componentDidMount() {
    }
    createForum = async(userId) =>{
        // console.log(this.state.title)
        if (this.state.title === null) {
            return
        }else if(this.state.title === ''){
            return
        }else {
            const response = await createForumRequest(user.id)
            // console.log(response)
            this.setState({
                fourmId:response.fourmId
            })
        }

    }
    onUploadImg = async (files, callback) => {
        // const res = await Promise.all(
        //     files.map((file) => {
        //         return new Promise((rev, rej) => {
        //             const form = new FormData();
        //             form.append('file', file);
        //
        //             axios
        //                 .post('/api/img/upload', form, {
        //                     headers: {
        //                         'Content-Type': 'multipart/form-data'
        //                     }
        //                 })
        //                 .then((res) => rev(res))
        //                 .catch((error) => rej(error));
        //         });
        //     })
        // );
        // callback(res.map((item) => item.data.url));
        if(this.state.fourmId === null) return
        formdata.append('Img',files[0])
        const response = await uploadImgRequest(formdata,this.state.fourmId)
        const ImgUrl= process.env.REACT_APP_BASE_URL+ response.img_path
        this.setState({
            text:this.state.text + '![]' + `(${ImgUrl})`
        })
    };
    onFinish = async(values) => {
        values['userid']=user.id
        values['fourmId'] = this.state.fourmId
        const response = await uploadForumRequest(values)
        if(response.code === '200'){
            this.setState({
                text:'',
                title:''
            })
            toast.success('发布成功', {
                autoClose: 1000,
            });
            setTimeout(() => {
                this.props.history.push('/Forum')
            },1000)
        }
    }
    setText = (event) => {
        this.setState({
            text:event
        })
    }
    render() {
        return (
            <div className='center'>
                {/*<h1>1111</h1>*/}
                <div className ={style.box}>
                    <h1>发布文章</h1>
                    <div className={style.body}>
                        <Form
                            name="basic"
                            labelCol={{
                                span: 8,
                            }}
                            wrapperCol={{
                                span: 16,
                            }}
                            style={{
                                // maxWidth: 600,
                                // border:'1px solid red'
                                position:'relative'
                            }}
                            onFinish={this.onFinish}
                            // autoComplete="off"
                            // className = {style.form}
                        >
                            <Form.Item
                                label="标题"
                                name="title"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入标题',
                                    },
                                ]}
                                style={{
                                    position:'relative',
                                    left:'-10vw'
                                }}
                            >
                                <Input onBlur={this.createForum} value={this.state.title} onChange={this.setTitle}  style = {

                                    {border:'1px solid red'}}/>
                            </Form.Item>

                            <Form.Item label = '文章内容' name='text' rules={[
                                {
                                    required: true,
                                    message: '请输入内容',
                                },
                            ]} style={{position:'relative',left:'-10vw'}}>
                                <MdEditor modelValue={this.state.text} onChange={this.setText} onUploadImg={this.onUploadImg} />
                            </Form.Item>
                            <Form.Item
                                wrapperCol={{
                                    offset: 8,
                                    span: 16,
                                }}
                            >
                                {/*<Button type="primary" htmlType="submit" style={{marginLeft:'120px'}}>*/}
                                {/*    发布*/}
                                {/*</Button>*/}
                                <button type='submit' style={{marginLeft:'120px',border:'0',width:'15vw',height:'8vh',backgroundColor:'skyblue',color:'white' }}>发布</button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>

            </div>
        );
    }
}

export default withRouter(ReleaseForum);